package project.tool4nat.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import static project.tool4nat.common.Constants.CID_LENGTH;
import static project.tool4nat.common.Constants.TYPE_LENGTH;

public class DataPackDecoder extends LengthFieldBasedFrameDecoder {

    public DataPackDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf buf = (ByteBuf) super.decode(ctx, in);
        if (buf == null) {
            return null;
        }
        DataPack dataPack = new DataPack();
        int length = buf.readInt();
        byte type = buf.readByte();
        long cid = buf.readLong();
        byte[] data = null;
        if (length > TYPE_LENGTH + CID_LENGTH) {
            data = new byte[length - TYPE_LENGTH - CID_LENGTH];
            buf.readBytes(data);
        }
        dataPack.setType(type);
        dataPack.setCid(cid);
        dataPack.setData(data);
        buf.release();
        return dataPack;
    }
}
